
/**
 * Module dependencies.
 */

var express = require('express')
  , logs = require('./conf/logs')
  , config = require('./conf/config')
  , settings = require('./conf/settings')
  , path = require('path')
  , http = require('http')
  , https = require('https')
  , fs = require('fs')
  , async = require("async");

// 测试环境之用
global.client_id = '3799249803934DE99495C9584AE68449';
global.client_secret = 'F07B8035741F42D7A0D7F6F71F98CB1A';

var httpServerStart = function(app){
	http.createServer(app).listen(config.httpPort, function(){
		console.info('schedule http server listening on port %s ', config.httpPort);
	});
};

var httpsServerStart = function(app){
	var privatekey = fs.readFileSync(path.join(config.root, 'certificate/privatekey.pem'), 'utf8');
	var certificate = fs.readFileSync(path.join(config.root, 'certificate/certificate.pem'), 'utf8');
	var options={key:privatekey, cert:certificate};
	https.createServer(options, app).listen(config.httpsPort, function(){
		console.info('schedule https server listening on port %s ', config.httpsPort);
	});
};

async.each([config.logPath], function(path, callback){
	fs.readdir(path, function(err, result){
		if (err) {
			console.info('正初始文件目录：%s', path);
			fs.mkdir(path, function(_err){
				callback(_err);
			});
		} else {
			callback(err);
		}
	});
},function(err){
	if (err) {
		console.error('初始化工程目录出错：%s', err);
	} else {
		var app = express();
		logs.init();
		settings(app, config);
		require('./conf/routes')(app);
		httpServerStart(app);
		httpsServerStart(app);
	}
});
